﻿using B.S.BaseData.ErrorCode;
using B.S.BaseData.Manage.Api.Read.Apilaction.Command.StoreCommand;
using B.S.BaseData.Manage.Api.Read.DTO;
using B.S.DataBase.Traceability.Infrastructure.Interface;
using B.S.Passport.Domain;
using DAL;
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.BaseData.Manage.Api.Read.Apilaction.CoomandHandler.StoreCommandHandler
{
    /// <summary>
    /// 入库显示
    /// </summary>
    public class StoreQuserCommandHandler : IRequestHandler<StoreQuserCommand, ApiReqult<ApIPageing<ManagementModelDTO>>>
    {
        private readonly DBHelper bHelper;

        public StoreQuserCommandHandler(DBHelper bHelper)
        {
            this.bHelper = bHelper;
        }

        public async Task<ApiReqult<ApIPageing<ManagementModelDTO>>> Handle(StoreQuserCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiReqult<ApIPageing<ManagementModelDTO>>();
            result.Code = ApiEnum.查询成功;
            result.Msg = ApiEnum.查询成功.ToString();

            var list = $"SELECT * FROM (SELECT mm.* FROM ManagementModels mm ORDER BY mm.Id DESC OFFSET (({request.PageIdex}-1)*{request.PageSize}) ROWS FETCH NEXT {request.PageSize} ROWS ONLY) as temp WHERE IsDelete = 0";
            if (!string.IsNullOrEmpty(request.InboundNum))
            {
                list += $" and InboundNum = '{request.InboundNum}'";
            }

            if (request.Storage != null)
            {
                // 假设 Storage 是 int 类型，去掉单引号
                list += $" and Storage = {request.Storage}";
            }

            if (request.OutAuditstatus != null)
            {
                // 假设 OutAuditstatus 是 int 类型，去掉单引号
                list += $" and OutAuditstatus = {request.OutAuditstatus}";
            }

            var sql = "SELECT COUNT(*) FROM ManagementModel mm LEFT JOIN ProductModel pm ON mm.Pid = pm.ProductId";

            ApIPageing<ManagementModelDTO> apiPaging = new ApIPageing<ManagementModelDTO>();
            apiPaging.TotalCount = (int)bHelper.Scalar(sql);
            apiPaging.TotalPage = (int)Math.Ceiling(apiPaging.TotalCount * 1.0 / request.PageSize);

            apiPaging.List = bHelper.GetList<ManagementModelDTO>(list);
            result.Data = apiPaging;

            return result;
        }
    }
}